package com.geekteam.masterenglish.ui;

import java.util.ArrayList;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.geekteam.masterenglish.R;
import com.geekteam.masterenglish.Adapter.NavigationListAdapter;
import com.geekteam.masterenglish.service.EEService;
import com.geekteam.masterenglish.service.MediaPlaybackService;
import com.geekteam.masterenglish.service.MediaPlaybackService.LocalBinder;
import com.geekteam.masterenglish.service.MediaPlaybackService.OnMusicLisener;
import com.geekteam.masterenglish.service.MediaPlaybackService.State;
import com.geekteam.masterenglish.ui.BaseActivity.OnFragmentChangeListener;
import com.geekteam.masterenglish.ui.fragment.HomeFragment;
import com.geekteam.masterenglish.ui.fragment.ListLessionFragment;
import com.geekteam.masterenglish.ui.fragment.ListListenFragment;
import com.geekteam.masterenglish.utils.Constants.BundleKey;
import com.geekteam.masterenglish.utils.Constants.TypeRequest;
import com.geekteam.masterenglish.utils.Utils;

public class MainActivity extends BaseActivity implements OnNavigationListener,
		OnFragmentChangeListener, OnClickListener, OnSeekBarChangeListener, OnMusicLisener,
		OnShowMenu{

	private static final String TAG = "MainActivity";
	private int mNavigationPosition;
	private long mBackPressed;
	private boolean isFirstHome;
	private LinearLayout mPlayingLayout;
	private TextView mTitleLession;
	private ImageView mStartButton;
	private TextView mCurrentTime;
	private TextView mTotalTime;
	private SeekBar mSeekBar;
	private MediaPlaybackService mService;
	private boolean mBound = false;
	private Handler mHandler;
	private String mTitle;
	private String mBook;
	private String mDownloadUrl;
	private MenuItem mSettingItem;
	private MenuItem mDownloadItem;
	private MenuItem mTutorialItem;
	
	private Runnable mUpdateTimeTask = new Runnable() {
		
		@Override
		public void run() {
			if(mBound){
				long currentDuration = mService.getCurrentPosition();
				long totalDuration = mService.getDuration();
				int progress = Utils.getProgressPercentage(currentDuration, totalDuration);
				
				mCurrentTime.setText(Utils.milliSecondsToTimer(currentDuration));
				mTotalTime.setText(Utils.milliSecondsToTimer(totalDuration));
				mSeekBar.setProgress(progress);
			}
			mHandler.postDelayed(mUpdateTimeTask, 100);
		}
	};
	
	private ServiceConnection mConnection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			mBound = false;
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			LocalBinder binder = (LocalBinder) service;
			mService = binder.getService();
			mService.setOnMusicLisener(MainActivity.this);
			mBound = true;
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		isFirstHome = true;
		if (savedInstanceState != null) {
			mNavigationPosition = savedInstanceState
					.getInt(BundleKey.NAVIGATION_POS);
		} else {
			mNavigationPosition = 0;
		}

		setContentView(R.layout.activity_main);
		
		//init music player
		mPlayingLayout = (LinearLayout) findViewById(R.id.now_playing);
		mTitleLession = (TextView) findViewById(R.id.title_lession);
		mStartButton = (ImageView) findViewById(R.id.start_lession);
		mCurrentTime = (TextView) findViewById(R.id.current_time);
		mTotalTime = (TextView) findViewById(R.id.total_time);
		mSeekBar = (SeekBar) findViewById(R.id.seekBar1);
		mStartButton.setOnClickListener(this);
		mSeekBar.setOnSeekBarChangeListener(this);
		
		//init view pager fragment
		setFragmentChangeListener(this);
		ArrayList<Fragment> listFragment = new ArrayList<Fragment>();
		listFragment.add(new ListListenFragment());
		listFragment.add(new ListLessionFragment());
		listFragment.add(new ListListenFragment());

		mContent = new HomeFragment(0, listFragment);
		switchFragment(mContent);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt(BundleKey.NAVIGATION_POS, mNavigationPosition);
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onStart() {
		super.onStart();
		Intent intent = new Intent(this, MediaPlaybackService.class);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
		if(mHandler!=null){
			mHandler.removeCallbacks(mUpdateTimeTask);
		}
	}
	
	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		mNavigationPosition = itemPosition;
		if (itemPosition != 0 && isFirstHome) {
			isFirstHome = false;
		}

		if (itemPosition == 0 && isFirstHome) {
			return true;
		} else if (mContent != null && mContent instanceof HomeFragment) {
			((HomeFragment) mContent).setPosition(itemPosition);
		}

		return true;
	}

	@Override
	public void onBackPressed() {
		if (getSupportFragmentManager().getBackStackEntryCount() == 2) {
			onFragmentChange(true);
			onHideMenuDownload();
		}

		if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
			if (mBackPressed + 2000 > System.currentTimeMillis()) {
				finish();
			} else {
				Toast.makeText(getBaseContext(),
						getString(R.string.press_again), Toast.LENGTH_SHORT)
						.show();
				mBackPressed = System.currentTimeMillis();
			}
		} else {
			super.onBackPressed();

		}
	}

	public void setNavigationPosition(int position) {
		mNavigationPosition = position;
		getSupportActionBar().setSelectedNavigationItem(mNavigationPosition);
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.main, menu);
        mSettingItem = menu.findItem(R.id.action_settings);
        mDownloadItem = menu.findItem(R.id.action_download);
        mTutorialItem = menu.findItem(R.id.action_tutorial);
        mDownloadItem.setVisible(false);
        return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			return true;
		case R.id.action_download:
			menuDownloadClick();
			return true;
		case R.id.action_settings:
			menuSettingClick();
			return true;
		case R.id.action_tutorial:
			menuTutorialClick();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onFragmentChange(boolean isHome) {
		if (isHome) {
			getSupportActionBar().setDisplayShowTitleEnabled(false);
			TypedArray titles = getResources().obtainTypedArray(R.array.title);
			NavigationListAdapter navigationListApdater = new NavigationListAdapter(
					getBaseContext(), titles);
			getSupportActionBar().setNavigationMode(
					ActionBar.NAVIGATION_MODE_LIST);
			getSupportActionBar().setListNavigationCallbacks(
					navigationListApdater, this);
			getSupportActionBar()
					.setSelectedNavigationItem(mNavigationPosition);
			getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		} else {
			getSupportActionBar().setNavigationMode(
					ActionBar.DISPLAY_SHOW_TITLE);
			getSupportActionBar().setDisplayShowTitleEnabled(true);
			getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	public void showMediaPlayer() {
		mPlayingLayout.setVisibility(View.VISIBLE);
		Log.d(TAG, "show media player");
	}

	public void hideMediaPlayer() {
		mPlayingLayout.setVisibility(View.GONE);
		Log.d(TAG, "hide media player");
		//TODO maybe stop music when hide media player
		if(mBound){
			
		}
	}

	public void playMusic(String url, String title, String book, String downloadUrl) {
		if(mBound){
			mService.startLession(url, title);
			if(mHandler ==null){
				mHandler = new Handler();
			}
			
			mHandler.post(mUpdateTimeTask);
		}
		mTitle = title;
		mDownloadUrl = downloadUrl;
		mBook = book;
		mTitleLession.setText(getString(R.string.buffering));
		mSeekBar.setSecondaryProgress(0);
	}

	@Override
	public void onClick(View view) {
		if(mBound){
			if(mService.isPlaying()){
				mService.pause();
				mStartButton.setImageResource(R.drawable.ic_action_play);
			}else{
				mService.start();
				mStartButton.setImageResource(R.drawable.ic_action_pause);
			}
		}
	}

	@Override
	public void onProgressChanged(SeekBar seekbar, int position, boolean isUserChange) {}

	@Override
	public void onStartTrackingTouch(SeekBar seekbar) {
		mHandler.removeCallbacks(mUpdateTimeTask);
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekbar) {
		if(mBound){
			mHandler.removeCallbacks(mUpdateTimeTask);
			int totalDuration = mService.getDuration();
			int currentPosition = Utils.progressToTimer(seekbar.getProgress(), totalDuration);
			
			mService.seekTo(currentPosition);
			mHandler.postDelayed(mUpdateTimeTask, 100);
		}
	}

	@Override
	public void onBufferingUpdate(int percent) {
		mSeekBar.setSecondaryProgress(percent);
	}

	@Override
	public void onError(int code, String message) {
		
	}

	@Override
	public void onStateChange(State state) {
		if(state.equals(State.Playing) || state.equals(State.Paused)){
			mTitleLession.setText(mTitle);
		}else{
			mTitleLession.setText(getString(R.string.buffering));
		}
	}

	@Override
	public void onShowMenuDownload() {
		if(mDownloadItem!=null){
			mDownloadItem.setVisible(true);
			mSettingItem.setVisible(false);
			mTutorialItem.setVisible(false);
		}
	}

	@Override
	public void onHideMenuDownload() {
		if(mDownloadItem!=null){
			mDownloadItem.setVisible(false);
			mSettingItem.setVisible(true);
			mTutorialItem.setVisible(true);
		}
	}
	
	private void menuSettingClick(){
		Intent intent = new Intent(this, SettingActivity.class);
		startActivity(intent);
	}
	
	private void menuTutorialClick(){
		
	}
	
	private void menuDownloadClick(){
		Intent intent = new Intent(this, EEService.class);
		intent.putExtra(BundleKey.URL, mDownloadUrl);
		intent.putExtra(BundleKey.TITLE, mTitle);
		intent.putExtra(BundleKey.BOOK, mBook);
		intent.putExtra(BundleKey.TYPE_REQUEST, TypeRequest.DOWNLOAD);
		startService(intent);
	}
}
